package org.example.controller.platform;

import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.common.result.Result;
import org.example.entity.Permission;
import org.example.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 平台端 权限相关接口，
 */
@RestController
@RequestMapping("/platform/permissions")
@Slf4j
@Tag(name = "平台端-权限管理", description = "平台端权限管理相关接口")
@SecurityRequirement(name = "platformBearerAuth")
public class PermissionController {

    @Autowired
    private RoleService roleService; // 复用 roleService.getPlatformPermissions()

    /**
     * 权限树（平台端）
     */
    @GetMapping("/tree")
    public Result<List<Map<String, Object>>> getPlatformPermissionTree() {
        try {
            List<Permission> all = roleService.getPlatformPermissions();
            Map<String, Permission> codeToPerm = new HashMap<>();
            for (Permission p : all) {
                if (p != null && p.getPermissionCode() != null) {
                    codeToPerm.put(p.getPermissionCode(), p);
                }
            }

            // 固定别名ID（仅用于前端展示和提交，后端会转换为DB真实id）
            Map<String, Integer> codeToAliasId = new HashMap<>();
            codeToAliasId.put("platform:list:view", 101);
            codeToAliasId.put("platform:list:approve", 102);
            codeToAliasId.put("platform:settlement:view", 103);
            codeToAliasId.put("platform:settlement:export", 104);
            codeToAliasId.put("platform:enterprise:view", 105);
            codeToAliasId.put("platform:feedback:reply", 106);
            codeToAliasId.put("platform:report:manage", 107);

            // 预定义平台端分组与包含的权限code（按你的示例）
            Map<String, List<String>> groupToCodes = new LinkedHashMap<>();
            groupToCodes.put("清单管理", Arrays.asList(
                "platform:list:view",
                "platform:list:approve"
            ));
            groupToCodes.put("结算管理", Arrays.asList(
                "platform:settlement:view",
                "platform:settlement:export"
            ));
            groupToCodes.put("企业管理", Arrays.asList(
                "platform:enterprise:view"
            ));
            groupToCodes.put("意见反馈", Arrays.asList(
                "platform:feedback:reply"
            ));
            groupToCodes.put("举报投诉", Arrays.asList(
                "platform:report:manage"
            ));

            List<Map<String, Object>> data = new ArrayList<>();
            for (Map.Entry<String, List<String>> entry : groupToCodes.entrySet()) {
                String group = entry.getKey();
                List<String> codes = entry.getValue();
                List<Map<String, Object>> children = new ArrayList<>();
                for (String code : codes) {
                    Permission p = codeToPerm.get(code);
                    if (p == null) {
                        // 未在数据库中找到对应权限时跳过，避免返回空节点
                        continue;
                    }
                    Map<String, Object> item = new LinkedHashMap<>();
                    Integer displayId = codeToAliasId.get(code);
                    item.put("id", p.getId());
                    item.put("code", p.getPermissionCode());
                    item.put("name", p.getPermissionName());
                    item.put("type", p.getPermissionType());
                    if (displayId != null) {
                        item.put("displayId", displayId);
                    }
                    children.add(item);
                }
                if (!children.isEmpty()) {
                    Map<String, Object> groupNode = new LinkedHashMap<>();
                    groupNode.put("group", group);
                    groupNode.put("children", children);
                    data.add(groupNode);
                }
            }

            return Result.success(data);
        } catch (Exception e) {
            log.error("获取平台权限树失败", e);
            return Result.error("获取平台权限树失败");
        }
    }
}